<template>
  <view>
    <scroll-view>
      <uni-list :border="true">
        <view v-for="user in userList" :key="user.userId">
          <uni-list-chat
            clickable
            @click="clickUser(user.userId)"
            v-if="user.userId != userInfo.id"
            :avatar-circle="true"
            :title="user.userName"
            :avatar="getImage(user.avatarId)"
            :badge-text="user.userId in messageCounts ? messageCounts[user.userId] : 0"
            :note="user.userId in newMessages ? newMessages[user.userId] : ''"></uni-list-chat
        ></view>
      </uni-list>
    </scroll-view>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  computed: {
    ...mapGetters(['userInfo']),
  },
  data() {
    return {
      userList: [],
      newMessages: {},
      messageCounts: {},
    }
  },
  onLoad() {
    this.onConnection()
  },
  methods: {
    onConnection() {
      this.$store.dispatch('message/initSocket', this.onMessage, this.onError)
    },
    // 接收消息
    onMessage(e) {
      var data = JSON.parse(e.data)
      switch (data.type) {
        case 1:
          this.userList = data.content
          break
        case 2:
          this.newMessages[data.from] = data.content
          this.messageCounts[data.from] = data.from in this.messageCounts ? this.messageCounts[data.from] + 1 : 1
          break
      }
    },
    // 错误
    onError(e) {
      console.log(e)
    },
    // 点击用户
    clickUser(id) {
      this.messageCount = 0
      uni.navigateTo({
        url: `/pages/chat/chat?id=${id}&name=${this.userList[id].userName}&avatarId=${this.userList[id].avatarId}`,
      })
    },
    // 获取头像
    getImage(id) {
      return `${process.env.VUE_APP_ORIGIN_API}fileService/file/download?id=${id}`
    },
  },
}
</script>
<style lang="scss" scoped></style>
